#!/usr/bin/env bash
# hdkernel - a linker for HALVM
# Usage: to be invoked from ghc using "ghc -pgml ldkernel"
#
# BANNERSTART
# - Copyright 2006-2008, Galois, Inc.
# - This software is distributed under a standard, three-clause BSD license.
# - Please see the file LICENSE, distributed with this software, for specific
# - terms and conditions.
# Author: Andrew Tolmach <apt@galois.com>
# Contributor: Adam Wick <awick@galois.com>
# BANNEREND
#

#echo "--------"
#echo $*
#echo "--------"

# Collect object files and the name of the executable from the arguments
# supplied by GHC. Ignore other arguments.
#objs=""
#while [ $# != 0 ] ; do
#  case "$1" in
#    *.o) objs="$1 $objs" ;;
#    -o) objs="$objs $1 $2"; shift;;
#  esac
#  shift
#done

prefix="@prefix@"
exec_prefix="@exec_prefix@"
libdir="@libdir@"
halvm_dir="@libdir@/HaLVM-@PACKAGE_VERSION@"

# reset the arguments as the file content of the path provided in the original argument
if [[ ${1:0:1} == "@" ]]; then
  set -- $(cat $(echo $@ | sed 's/^@//') | tr '\n' ' ' | sed 's/\"//g')
fi

# Uncomment below to debug linker options.
warn_ignored () {
    # echo "WARNING: ignoring linker option in $0: $1"
    :
}

ARGS=""
LIBS=""
LIBDIR=`echo $0 | sed 's/[^/]*$//g'`
START_FILE="${halvm_dir}/rts-1.0/start.o"
LIBM_FILE="${halvm_dir}/rts-1.0/libopenlibm.a"
LINKER_SCRIPT="-T ${halvm_dir}/kernel.lds"
while [ $# != 0 ] ; do
  case "$1" in
    "-DDONT_WANT_WIN32_DLL_SUPPORT") warn_ignored "$1"; shift;;
    -u) warn_ignored "$1 $2"; shift; shift;;
    -lm) warn_ignored "$1"; shift;;
    -ldl) warn_ignored "$1"; shift;;
    -lrt) warn_ignored "$1"; shift;;
    -l*) LIBS="$LIBS $1"; shift;;
    -Wl,-r) ARGS="$ARGS -r"; LINKER_SCRIPT=""; START_FILE=""; shift;;
    -Wl,-x) ARGS="$ARGS -x"; LINKER_SCRIPT=""; START_FILE=""; shift;;
    -Wl,-u*) BIT=`echo "$1" | cut -c 8-`; ARGS="$ARGS -u ${BIT}"; shift;;
    -Wl,--reduce-memory-overheads) ARGS="${ARGS} --reduce-memory-overheads";shift;;
    -Wl,--hash-size*) BIT=`echo "$1"|cut -c 17-`;ARGS="$ARGS -u ${BIT}";shift;;
    -Wl,--version) ARGS="$ARGS --version"; shift;;
    -Wl,--no-as-needed) ARGS="$ARGS --no-as-needed"; shift;;
    -Wl,--build-id=none) TY=$(echo "$1" | cut -c 16-); ARGS="$ARGS --build-id=${TY}"; shift;;
    # HACK (izgzhen): don't know a better way to handle this
    -Wl,--gc-sections) warn_ignored "$1"; shift;;
    # This option confuses GNU ld. The gcc command supports '-no-pie'
    # and '-pie', but 'ld' only supports '-pie'. It's possible that a
    # better thing to here is see if '-pie' is an earlier option, and
    # remove it if so.
    -no-pie) warn_ignored "$1"; shift;;
    *) ARGS="$ARGS $1"; shift;;
  esac
done

LDCMD="ld ${LINKER_SCRIPT} -nostdlib ${START_FILE} $ARGS $LIBS -L${halvm_dir}/rts-1.0 ${LIBM_FILE} -lminlibc"
#echo $LDCMD
$LDCMD
